package com.ruoyi.womp.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.ruoyi.common.utils.security.PermissionUtils;
import com.ruoyi.womp.domain.WompOsiRecord;
import com.ruoyi.womp.domain.WompOsiRecordItem;
import com.ruoyi.womp.domain.WompWorkOrder;
import com.ruoyi.womp.tools.DateUtil;

@Service
public class RealTimeServie {

	final String alarmTable = "womp_alarm_data";

	@Autowired
	ISqlQueryService sqlQueryService;

	@Autowired
	private IWompWorkOrderService wompWorkOrderService;

	@Autowired
	IWompOsiRecordService wompOsiRecordService;

	@Autowired
	MongoTemplate mongoTemplate;

	public Map<String, Object> getAlarmInfo(String alarmId) {

		Query query = new Query();
		query.addCriteria(Criteria.where("_id").is(alarmId));
		Map<String, Object> wompAlarm = mongoTemplate.findById(new ObjectId(alarmId), Map.class, alarmTable);

		return wompAlarm;
	}

	public void putToken(HttpServletRequest req, Model model) {
		String token = req.getParameter("token");

		model.addAttribute("token", token);
	}

	@Transactional
	public void saveWorkOrder(HttpServletRequest req) {

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");

		String alarmId = req.getParameter("alarmId");
		Map<String, Object> wompAlarm = mongoTemplate.findById(new ObjectId(alarmId), Map.class, alarmTable);

		String waCode = wompAlarm.get("waCode").toString();
		String type = req.getParameter("type");
		String elementCode = wompAlarm.get("code").toString();
		String handlingOpinions = req.getParameter("handlingOpinions");
		String handler = req.getParameter("handler");

		WompWorkOrder workOrder = new WompWorkOrder();
		workOrder.setWaCode(waCode);
		workOrder.setType(type);
		workOrder.setAlarmId(alarmId);
		workOrder.setEcode(elementCode);
		workOrder.setHandlingOpinions(handlingOpinions);
		workOrder.setHandler(handler);
		workOrder.setState(0);
		workOrder.setCreateBy(loginName);
		workOrder.setCreateTime(Calendar.getInstance().getTime());

		wompWorkOrderService.insertWompWorkOrder(workOrder);

		// 0未处理，1已处理，2已忽略，3已完成
		alarmChangeState(alarmId, 1);
	}

	public void alarmChangeState(String alarmId, Integer state) {
		Query query = new Query(Criteria.where("_id").is(alarmId));
		Update update = new Update().set("state", state);
		mongoTemplate.updateFirst(query, update, alarmTable);
	}

	@Transactional
	public void handleWorkOrder(HttpServletRequest req) {

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");
		Integer workOrderId = Integer.parseInt(req.getParameter("workOrderId"));
		String workorderType = req.getParameter("workorderType");
		String handleContent = req.getParameter("handleContent");

		if (workorderType.equals("1")) {
			Integer state = Integer.parseInt(req.getParameter("state"));
			String files = req.getParameter("files");

			WompWorkOrder workOrder = wompWorkOrderService.selectWompWorkOrderById(workOrderId);
			workOrder.setUpdateBy(loginName);
			workOrder.setState(state);
			workOrder.setHandleContent(handleContent);
			workOrder.setFiles(files);
			wompWorkOrderService.updateWompWorkOrder(workOrder);
		} else if (workorderType.equals("2")) {
			String waCode = req.getParameter("waCode");
			String osiUser = req.getParameter("osiUser");
			String osiDate = req.getParameter("osiDate");
			Integer osiType = Integer.parseInt(req.getParameter("osiType"));

			// 更新工单状态
			WompWorkOrder workOrder = wompWorkOrderService.selectWompWorkOrderById(workOrderId);
			workOrder.setHandleContent(handleContent);
			workOrder.setState(1);
			workOrder.setHandler(osiUser);
			workOrder.setUpdateBy(loginName);
			wompWorkOrderService.updateWompWorkOrder(workOrder);
			// 存储巡检记录
			WompOsiRecord osiRecord = new WompOsiRecord();
			osiRecord.setWaCode(waCode);
			osiRecord.setWorkorderId(workOrderId);
			osiRecord.setOsiPlanType(osiType);
			osiRecord.setOsiUser(osiUser);
			try {
				osiRecord.setOsiDate(DateUtil.parseDate(osiDate, "yyyy-MM-dd"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			osiRecord.setRemark(handleContent);
			osiRecord.setCreateBy(DateUtil.sysDateTime());
			osiRecord.setCreateBy(loginName);

			List<WompOsiRecordItem> items = new ArrayList<WompOsiRecordItem>();
			int i = 0;
			while (true) {
				String osiItemIdString = req.getParameter("wompOsiRecordItemList[" + i + "].osiItemId");
				if (null == osiItemIdString) {
					break;
				}
				Integer osiItemId = Integer.parseInt(osiItemIdString);
				Integer osiResult = Integer.parseInt(req.getParameter("wompOsiRecordItemList[" + i + "].osiResult"));
				String remark = req.getParameter("wompOsiRecordItemList[" + i + "].remark");

				WompOsiRecordItem osiRecordItem = new WompOsiRecordItem();
				osiRecordItem.setOsiItemId(osiItemId);
				osiRecordItem.setOsiResult(osiResult);
				osiRecordItem.setRemark(remark);

				items.add(osiRecordItem);

				i++;
			}
			osiRecord.setWompOsiRecordItemList(items);

			wompOsiRecordService.insertWompOsiRecord(osiRecord);
		}
	}

	public Map<String, Object> getWorkOrderMap(String workOrderId) {
		String sql = " select wwo.id,wwo.type,wwo.wa_code,wwo.osi_type,wwo.alarm_id,wwo.ecode,wwo.handling_opinions,wwo.handler, "
				+ " ifnull(wwo.handle_content,'') handle_content,wwo.files,wwo.create_by,wwo.create_time,wwo.state,wwo.update_by, "
				+ " wwo.update_time,sdd1.dict_label workOrderState, "
				+ " sdd2.dict_label workOrderType,su.user_name handlerName from womp_work_order wwo "
				+ " inner join sys_dict_data sdd1 on sdd1.dict_value=wwo.state and sdd1.dict_type='work_order_state' "
				+ " inner join sys_dict_data sdd2 on sdd2.dict_value=wwo.type and sdd2.dict_type='work_order_type' "
				+ " inner join sys_user su on su.login_name=wwo.handler " + " where id='" + workOrderId + "' ";
		return sqlQueryService.queryOne(sql);
	}

	public List<Map> getAlarmInfoList(List<String> idList) {

		Query query = new Query();
		query.addCriteria(Criteria.where("_id").in(idList));

		List<Map> list = mongoTemplate.find(query, Map.class, alarmTable);

		return list;
	}

	public long getAlarmNum(String waCode) {

		Query query = new Query();
		query.addCriteria(Criteria.where("waCode").is(waCode));
		query.addCriteria(Criteria.where("state").is(0));

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR_OF_DAY, -24);
		query.addCriteria(
				Criteria.where("time").gte(DateUtil.formatDateTime(cal.getTime())).lte(DateUtil.sysDateTime()));

		// List<Map> list = mongoTemplate.find(query, Map.class, alarmTable);
		return mongoTemplate.count(query, alarmTable);
		// return 0;
	}

	public Map<String, Object> getWaInfoMap(String wacode) {
		String sql = " SELECT wa.code wacode,wa.name waname,wa.model,wa.spec,wa.index_chart_element,wat.code type,wat.name typename,wat.d3_annex,wa.index_chart_element,wa.alarm_music, "
				+ " (select count(*) from womp_element_config where element_code=wa.index_chart_element and wa_type=wat.code) index_chart_element_num, "
				+ " (select name from womp_element where code=wa.index_chart_element) index_chart_element_name "
				+ " FROM womp_weighing_apparatus wa inner join womp_weighing_apparatus_type wat on wa.type=wat.code "
				+ " where wa.code='" + wacode + "' ";
		return sqlQueryService.queryOne(sql);
	}

	public List<Map<String, Object>> getWaTypeConfigData(String type, String waCode) {
		String sql = " select we.name elementname,we.code,we.unit,wec.show_type,wec.order_num,wec.show_width,wec.point_label_lon,"
				+ " wec.point_label_lat,wec.line_wa_lon,wec.line_wa_lat,wec.line_side,wec.label_color,wec.sort_no,wec.title from womp_element_config wec "
				+ " inner join womp_element we on wec.element_code=we.code"
				+ " inner join womp_weighing_apparatus_element wwae on wec.element_code = wwae.element_code and wwae.wa_code='"
				+ waCode + "'" + "and wec.order_num = wwae.order_num where wec.wa_type='" + type
				+ "' order by we.code,wec.order_num,wec.sort_no ";

		return sqlQueryService.queryMapList(sql);
	}

	public List<Map<String, Object>> getWaTypeConfigColorData(String type) {
		String sql = " SELECT distinct element_code,label_color,we.name FROM womp_element_config wec inner join womp_element we on wec.element_code=we.code and wa_type='"
				+ type + "' and label_color is not null and show_type!=4 ";

		return sqlQueryService.queryMapList(sql);
	}

	public List<Map<String, Object>> getWaTypeConfigList() {
		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");

		String sql = " SELECT distinct element_code ,we.name FROM womp_weighing_apparatus_element wwae "
				+ " inner join womp_element we on wwae.element_code=we.code and wa_code IN "
				+ " ( SELECT wa.CODE wacode FROM womp_weighing_apparatus wa INNER JOIN womp_weighing_apparatus_type wat "
				+ " ON wa.type = wat.CODE WHERE FIND_IN_SET( user_id, ( SELECT dept_id FROM sys_user WHERE login_name = '"
				+ loginName + "' ))) ";

		return sqlQueryService.queryMapList(sql);
	}

	public List<Map<String, Object>> getDeptWeighingApparatusList(String userId) {
		String sql = " SELECT wa.code wacode,wa.name waname,wa.model,wa.type watype,DATE_FORMAT(wa.install_date,'%Y-%m-%d') install_date,wa.spec,wat.code type,wat.name typename,wat.d3_annex "
				+ " FROM womp_weighing_apparatus wa inner join womp_weighing_apparatus_type wat on wa.type=wat.code "
				+ "	where FIND_IN_SET(user_id,(SELECT dept_id FROM sys_user where login_name='" + userId + "')) ";

		List<Map<String, Object>> waList = sqlQueryService.queryMapList(sql);

		for (Map<String, Object> map : waList) {
			long num = getAlarmNum(map.get("wacode").toString());
			map.put("alarmNum", num);
		}

		return waList;
	}

	public Map<String, Object> getDeptDefaultWeighingApparatus(String userId) {
		String sql = " SELECT wa.code wacode,wa.name waname,wa.model,wa.spec,wat.code type,wat.name typename,wat.d3_annex,wa.index_chart_element,wa.alarm_music,wa.is_def, "
				+ " (select count(*) from womp_element_config where element_code=wa.index_chart_element and wa_type=wat.code) index_chart_element_num, "
				+ " (select name from womp_element where code=wa.index_chart_element) index_chart_element_name "
				+ " FROM womp_weighing_apparatus wa inner join womp_weighing_apparatus_type wat on wa.type=wat.code "
				+ "	where FIND_IN_SET(user_id,(SELECT dept_id FROM sys_user where login_name='" + userId + "')) ";

		List<Map<String, Object>> list = sqlQueryService.queryMapList(sql);
		Map<String, Object> waMap = null;
		for (Map<String, Object> map : list) {
			if (null != map.get("is_def") && map.get("is_def").toString().equals("Y")) {
				waMap = map;
			}
		}
		if (null == waMap && null != list && list.size() > 0) {
			waMap = list.get(0);
		}
		return waMap;
	}

	public List<Map<String, Object>> getWorkOrderList(String waCode, String type, String alarmId, Integer state,
			String ecode, String beginDate, String endDate) {
		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");

		String sql = " SELECT wwo.id,wwo.wa_code,wwo.type,wwo.osi_type,wea.name waname,wwo.files,wwo.alarm_id,wwo.state,wwo.ecode,we.name,wwo.handling_opinions, "
				+ "wwo.handler,su.user_name,handle_content,wwo.update_by,wwo.update_time,wwo.create_by,wwo.create_time "
				+ " FROM womp_work_order wwo left join womp_weighing_apparatus wea on wwo.wa_code=wea.code "
				+ " left join womp_element we ON wwo.ecode = we.CODE left join sys_user su on su.login_name=wwo.handler where 1=1 ";

		if (!loginName.equals("admin")) {
			sql += " and handler='" + loginName + "' ";
		}
		if (null != waCode && waCode.length() > 0) {
			sql += " and wwo.wa_code='" + waCode + "'";
		}
		if (null != type && type.length() > 0) {
			sql += " and wwo.type='" + type + "'";
		}
		if (null != alarmId && alarmId.length() > 0) {
			sql += " and wwo.alarm_id='" + alarmId + "'";
		}
		if (null != ecode && ecode.length() > 0) {
			sql += " and wwo.ecode='" + ecode + "'";
		}
		if (null != state) {
			sql += " and wwo.state=" + state;
		}
		if (null != beginDate && beginDate.length() > 0 && null != endDate && endDate.length() > 0) {
			sql += " and wwo.create_time between '" + beginDate + " 00:00:00' and '" + endDate + " 23:59:59' ";
		}

		sql += " order by wwo.create_time desc ";

		return sqlQueryService.queryMapList(sql);
	}

	public void allIgnoreAlarm() {

		Query query = new Query();
		query.addCriteria(Criteria.where("state").is(0));

		Update update = new Update().set("state", 2);
		mongoTemplate.updateMulti(query, update, alarmTable);
	}

	public void conditionIgnoreAlarm(HttpServletRequest req) {

		String waCode = req.getParameter("waCode");
		String ecode = req.getParameter("ecode");
		String alarmState = req.getParameter("alarmState");
		String beginDate = req.getParameter("beginDate");
		String endDate = req.getParameter("endDate");

		Query query = new Query();
		if (null != waCode && waCode.trim().length() > 0) {
			query.addCriteria(Criteria.where("waCode").is(waCode));
		}
		if (null != ecode && ecode.length() > 0) {
			query.addCriteria(Criteria.where("code").is(ecode));
		}
		if (null != alarmState && alarmState.length() > 0) {
			query.addCriteria(Criteria.where("state").is(Integer.parseInt(alarmState)));
		}
		if (null != beginDate && beginDate.length() > 0 && null != endDate && endDate.length() > 0) {
			query.addCriteria(Criteria.where("time").gte(beginDate + " 00:00:00").lte(endDate + " 23:59:59"));
		}

		Update update = new Update().set("state", 2);
		mongoTemplate.updateMulti(query, update, alarmTable);
	}

	public void checkIgnoreAlarm(HttpServletRequest req) {

		String alarmIds = req.getParameter("ids");

		if (null == alarmIds || alarmIds.length() == 0) {
			return;
		}
		String[] ids = alarmIds.split(",");
		for (String id : ids) {
			Query query = new Query(Criteria.where("_id").is(id));
			Update update = new Update().set("state", 2);
			mongoTemplate.updateFirst(query, update, alarmTable);
		}
	}
	
	public void conditionDeleteAlarm(HttpServletRequest req) {

		String waCode = req.getParameter("waCode");
		String ecode = req.getParameter("ecode");
		String alarmState = req.getParameter("alarmState");
		String beginDate = req.getParameter("beginDate");
		String endDate = req.getParameter("endDate");

		Query query = new Query();
		if (null != waCode && waCode.trim().length() > 0) {
			query.addCriteria(Criteria.where("waCode").is(waCode));
		}
		if (null != ecode && ecode.length() > 0) {
			query.addCriteria(Criteria.where("code").is(ecode));
		}
		if (null != alarmState && alarmState.length() > 0) {
			query.addCriteria(Criteria.where("state").is(Integer.parseInt(alarmState)));
		}
		if (null != beginDate && beginDate.length() > 0 && null != endDate && endDate.length() > 0) {
			query.addCriteria(Criteria.where("time").gte(beginDate + " 00:00:00").lte(endDate + " 23:59:59"));
		}
		
		query.addCriteria(Criteria.where("state").is(0));

		mongoTemplate.remove(query, alarmTable);
	}

	public String getEname(String ecode) {
		String sql = " select name from womp_element where code='" + ecode + "' ";

		Map<String, Object> eleMap = sqlQueryService.queryOne(sql);
		if (null != eleMap) {
			return eleMap.get("name").toString();
		} else
			return "未知";
	}

	public void createWorkorder(String waCode, String osiType, String charger, String handing_opinions) {
		String sql = " insert into womp_work_order (type,wa_code,osi_type,handling_opinions,handler,create_by,create_time,state) "
				+ " values ('2','" + waCode + "','" + osiType + "','" + handing_opinions + "','" + charger
				+ "','sysadmin','" + DateUtil.sysDateTime() + "','0') ";
		sqlQueryService.executeSql(sql);
	}
}
